﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DBService.Admin
{
    public class CompanyManager
    {
        public List<ListSearchCompanies_Result> GetSearchedCompanies(string searchText)
        {
            using (var context = new revioEntities())
            {
                return context.ListSearchCompanies(searchText).ToList();
            }
        }

        public void RestoreCompany(int comID)
        {
            using (var context = new revioEntities())
            {
                var comp = context.Companies.Where(c => c.CompanyID == comID).FirstOrDefault();
                if (comp != null)
                {
                    comp.IsDeleted = null;
                    context.SaveChanges();
                }
            }
        }

        public List<ListDeletedCompanies_Result> GetDeletedCompanies(string searchText)
        {
            using (var context = new revioEntities())
            {
                return context.ListDeletedCompanies(searchText).ToList();
            }
        }

        public static void DeleteImage(string path)
        {
            try
            {
                System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + "/upload/" + path);
            }
            catch
            {
                //TODO: Log ex.
            }
        }

        public bool RemoveCompany(int companyId)
        {
            using (var context = new revioEntities())
            {
                var toDelete = context.Companies.Where(c => c.CompanyID == companyId).SingleOrDefault();

                if (toDelete == null)
                    return false;

                //if (toDelete.Gallery != null &&
                //    toDelete.Gallery.GalleryFiles != null &&
                //    toDelete.Gallery.GalleryFiles.Count > 0)
                //{
                //    foreach (var file in toDelete.Gallery.GalleryFiles)
                //    {
                //        DeleteImage(file.File.FilePath);
                //    }
                //}
                toDelete.IsDeleted = true;
                context.SaveChanges();

                //context.DeleteCompanyFull(companyId);

                //toDelete = context.Companies.Where(c => c.CompanyID == companyId).SingleOrDefault();
                //if (toDelete != null)
                //    return false;

                return true;
            }
        }
    }

    public class UserManager
    {
        public List<UserMan> GetUsersBy(DateTime dateFrom, DateTime dateTo)
        {
            /*
             select u.userid,r.review,COUNT(r.review) as coun,u.firstName,u.lastname,u.avatar,u.userid from reviews r
             inner join users u on u.userid=r.userid
             group by u.userid,review,u.firstName,u.lastname,u.avatar,u.userid
             order by coun desc
             */
            using (var context = new revioEntities())
            {
                var reviews = from r in context.Reviews.Where(r => r.CreateDate >= dateFrom && r.CreateDate <= dateTo && r.IsDeleted == null)
                              group r by new { r.Review1, r.User } into g
                              select new UserMan
                              {
                                  ID = g.Key.User.UserID,
                                  Avatar = g.Key.User.Avatar,
                                  LastName = g.Key.User.LastName,
                                  FirstName = g.Key.User.FirstName,
                                  Review = g.Key.Review1,
                                  Reviews = g.Count()
                              };
                return reviews.OrderByDescending(r => r.Reviews).ToList();
            }
        }

        public List<UserMan> GetUsersBy(int postsNumber, DateTime dateFrom, DateTime dateTo)
        {
            using (var context = new revioEntities())
            {
                var users = context.Users.Where(
                             u => u.Reviews.Where(r => r.CreateDate >= dateFrom && r.CreateDate <= dateTo).Count() > postsNumber)
                            .Select(u => new UserMan
                {
                    ID = u.UserID,
                    FirstName = u.FirstName,
                    LastName = u.LastName,
                    Avatar = u.Avatar,
                    Reviews = u.Reviews.Where(r => r.CreateDate >= dateFrom && r.CreateDate <= dateTo && r.IsDeleted == null).Count()
                }).ToList();
                return users;
            }
        }

        public List<UserMan> GetUsersBy(string userName)
        {
            using (var context = new revioEntities())
            {
                var users = context.Users.Where
                            (u => u.FirstName.Contains(userName) || u.LastName.Contains(userName))
                            .Select(u => new UserMan
                            {
                                ID = u.UserID,
                                FirstName = u.FirstName,
                                LastName = u.LastName,
                                Avatar = u.Avatar,
                                Reviews = u.Reviews.Where(r => r.IsDeleted == null).Count()
                            }).ToList();
                return users;
            }
        }

        public User GetUserBy(int id)
        {
            using (var context = new revioEntities())
            {
                return context.Users.Where(u => u.UserID == id).SingleOrDefault();
            }
        }

        public bool RemoveUserReviews(int userId)
        {
            using (var context = new revioEntities())
            {
                var reviews = context.Reviews.Where(r => r.UserID == userId);
                foreach (var item in reviews)
                {
                    item.IsDeleted = true;
                }
                context.SaveChanges();
                foreach (var item in reviews)
                {
                    ModelAdapter service = new ModelAdapter();
                    service.CalculateCompanyRating(item.CompanyID);
                }
                //var toDelete = context.Users.Where(c => c.UserID == userId).SingleOrDefault();

                //if (toDelete == null)
                //    return false;

                //foreach (var rev in toDelete.Reviews)
                //{
                //    foreach (var item in rev.Gallery.GalleryFiles)
                //    {
                //        try
                //        {
                //            CompanyManager.DeleteImage(item.File.FilePath);
                //        }
                //        catch (Exception ex)
                //        {
                //            // TODO log delete image exc.
                //        }
                //    }
                //}
                // context.DeleteUserReviews(userId);

                return true;
            }
        }

        public bool RemoveUsersSameReviews(int userId, string reviewText)
        {
            using (var context = new revioEntities())
            {
                var toDelete = context.Users.Where(c => c.UserID == userId).SingleOrDefault();
                ModelAdapter service = new ModelAdapter();
                if (toDelete == null)
                    return false;
                var reviews = toDelete.Reviews.Where(r => r.Review1 == reviewText);
                foreach (var rev in reviews)
                {
                    rev.IsDeleted = true;
                    context.SaveChanges();
                    service.CalculateCompanyRating(rev.CompanyID);
                    //foreach (var item in rev.Gallery.GalleryFiles)
                    //{
                    //    try
                    //    {
                    //        CompanyManager.DeleteImage(item.File.FilePath);
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        // TODO log delete image exc.
                    //    }
                    //}
                }
                //context.DeleteUsersSameReviews(userId, reviewText);
                context.SaveChanges();
                return true;
            }
        }
    }



    #region Admin Custom Entities
    public class UserMan
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Avatar { get; set; }
        public int Reviews { get; set; }
        public string Review { get; set; }
    }
    #endregion
}
